<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/8/3
 * Time: 15:09
 */

namespace app\api\controller\user;

use app\api\controller\BasicUserApi;
use service\WechatService;
use think\Db;
use think\Exception;

class Index extends BasicUserApi
{
    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function info(){
        try{
            //查询用户信息
            $member=Db::name('store_member')->where('id',UID)->hidden('password,level,remark,status,flag,openid')->find();
            $member['province_txt']=getmodel($member['province'],'system_city','name');
            $member['city_txt']=getmodel($member['city'],'system_city','name');
            $member['district_txt']=getmodel($member['district'],'system_city','name');
            switch ($member['type']){
                case USER_TYPE_WORKER:
                    $member['attach']=Db::name('worker_info')->where('mid',$member['id'])->find();
                    break;
                case USER_TYPE_SUPPLIER:
                    $member['attach']=Db::name('supplier_info')->where('mid',$member['id'])->find();
                    $member['attach']['images']=explode('|',$member['attach']['images']);
                    $member['attach']['supplier_type_arr']=Db::name('my_cate')
                        ->where('id','in',$member['attach']['supplier_type_ids'])->field('title')->select();
                    break;
            }
            if(isset($member['attach'])){
                $tip='';
                $expiry_time_class='';
                if($member['attach']['expiry_time']<time()){
                    //已过期
                    $expiry_time_class='red';
                    $tip='[已到期]';
                }elseif($member['attach']['expiry_time']-7*24*60*60<time()){
                    //七天后过期
                    $tip='[即将到期]';
                    $expiry_time_class='orange';
                }
                $member['attach']['expiry_time']=date('Y-m-d',$member['attach']['expiry_time']).$tip;
                $member['attach']['expiry_time_class']=$expiry_time_class;
            }
            return json(['msg'=>'success','data'=>$member]);
        }catch (Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 修改用户基本信息
     * @return \think\response\Json
     */
    public function update_user_info(){
        try{
            $post=$this->request->only(['headimg','nickname','phone','province','city','district','address','lng','lat'],'post');
            $validate=new \app\api\validate\Member();
            if(!$validate->check($post)){
                return json(['msg'=>$validate->getError()],403);
            }
            //修改用户信息
            Db::name('store_member')->where('id',UID)->update($post);
            return json(['msg'=>'信息修改成功']);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 获取用户个人中心数据
     * @return \think\response\Json
     */
    public function index()
    {
        $show_type=input('show_type',0);//查看方式 0：查看全部  1：查看新消息数量和浏览量 2：查看新消息数量
        switch ($show_type){
            case 0:
                $data['follow_num']=DB::name('member_follow')->where('uid',UID)->cache(60)->count();
                $data['article_num']=DB::name('article')->where('mid',UID)->cache(60)->count();
                //$data['pv']=DB::name('footprint')->where('supplier_mid',UID)->cache(60)->count();
                $data['pv']=DB::name('store_member')->where('id',UID)->value('browse');
                $data['new_msg_num']=Db::name('member_msg')->where('accepter_id',UID)
                    ->where('read_time',0)->count();//读取消息的时候注意更新缓存
                $data['service_tel']=config('jujin.service_tel');
                break;
            case 1:
                //$data['pv']=DB::name('footprint')->where('supplier_mid',UID)->cache(60)->count();
                $data['pv']=DB::name('store_member')->where('id',UID)->value('browse');
                $data['new_msg_num']=Db::name('member_msg')->where('accepter_id',UID)
                    ->where('read_time',0)->count();//读取消息的时候注意更新缓存
                break;
            case 2:
                $data['new_msg_num']=Db::name('member_msg')->where('accepter_id',UID)
                    ->where('read_time',0)->count();//读取消息的时候注意更新缓存
                break;
        }

        return json(['msg'=>'success','data'=>$data]);
    }

    /**
     * 获取推广小程序码
     * @return \think\response\Json
     */
    public function qr_code()
    {
        $file='/static/upload/qr_code/'.UID.'.jpg';
        if(!file_exists('.'.$file)){
            $sence=UID;
            $page='pages/login/login';
            $res=WechatService::WeMiniQrcode()->createMiniScene($sence,$page);
            file_put_contents('.'.$file,$res);
        }
        return json(['msg'=>'success','data'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$file]);
    }

    /**
     * 获取指定用户的聊天记录
     * @return \think\response\Json
     */
    public function chat_list()
    {
        try{
            $to_user_id=input('to_user_id');
            $map1=[
                ['sender_id', '=', UID],
                ['accepter_id', '=', $to_user_id]
            ];
            $map2=[
                ['sender_id', '=', $to_user_id],
                ['accepter_id', '=', UID]
            ];
            $list=Db::name('member_msg')
                ->whereOr([ $map1, $map2 ])
                ->order('id')->select();
            foreach ($list as $k=>&$v){
                $v['head_img']=getmodel($v['sender_id'],'store_member','headimg');
                $v['nickname']=getmodel($v['sender_id'],'store_member','nickname');
                $v['msg_type']='text';
            }
            //将目前未读消息置为已读
            Db::name('member_msg')
                ->where([
                    'sender_id'	=>	$to_user_id,
                    'accepter_id'=>	UID,
                    'read_time'=>	0,
                ])
                ->setField('read_time',time());
            return json(['msg'=>'success','data'=>$list]);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 设置消息为已读
     * @return \think\response\Json
     */
    public function read_msg(){
        try{
            $id=$this->request->get('id');
            //将这条未读消息置为已读
            Db::name('member_msg')
                ->where([
                    'id'	=>	$id,
                    'accepter_id'=>	UID,
                    'read_time'=>	0,
                ])
                ->setField('read_time',time());
            return json(['msg'=>'success']);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /*public function upload_voice()
    {
        var_dump($_POST);
    }*/

    /**
     * 获取用户消息列表
     * @return \think\response\Json
     */
    public function msg_list()
    {
        try{
            $list=Db::name('member_msg')->distinct(true)
                ->where('sender_id|accepter_id',UID)->field('sender_id,accepter_id')
                ->group('sender_id,accepter_id')->select();
            $sender_ids=array_column($list,'sender_id');
            $accepter_ids=array_column($list,'accepter_id');
            $uid_arr=array_unique(array_merge($sender_ids,$accepter_ids));
            //查询用户
            $member_list=Db::name('store_member')->where('id','in',implode(',',$uid_arr))
                ->where('id','<>',UID)->field('id,nickname,headimg')->select();
            foreach ($member_list as $k=>&$v){
                //查询与这个人的未读消息数量
                $v['new_msg_num']=Db::name('member_msg')->where('accepter_id',UID)
                    ->where('sender_id',$v['id'])->where('read_time',0)->count();
                //查询最近一条消息
                $last_msg=Db::name('member_msg')->where('sender_id|accepter_id',UID)
                    ->where('sender_id|accepter_id',$v['id'])
                    ->order('id desc')->field('content,FROM_UNIXTIME(create_at,\'%Y-%m-%d %H:%i:%s\') create_at')->find();
                $v['last_msg_content']=$last_msg['content'];
                $v['last_msg_create_at']=$last_msg['create_at'];
            }
            //数组排序
            foreach ($member_list as $key => $val) {
                $tmp[$key] = $v['last_msg_create_at'];
            }
            if($member_list){
                array_multisort($tmp,SORT_DESC,$member_list);
            }
            return json(['msg'=>'success','data'=>$member_list]);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 用户续费
     * @return mixed|\think\response\Json
     */
    public function renew(){
        try{
            //查询会员信息
            $code=$this->request->get('code');
            $grade_id=$this->request->get('grade_id');
            $token=input('token');
            $type=get_login_info($token,'type');
            /*switch ($type){
                case USER_TYPE_WORKER:
                    $grade_id=Db::name('worker_info')->where('mid',UID)->value('grade_id');
                    break;
                case USER_TYPE_SUPPLIER:
                    $grade_id=Db::name('supplier_info')->where('mid',UID)->value('grade_id');
                    break;
                default:
                    return json(['msg'=>'用户权限不足'],500);
            }*/
            //查询入驻等级
            $store_member_grade=Db::name('store_member_grade')
                ->where('id',$grade_id)
                ->where('type',$type)
                ->field('month,money,id')->find();
            if(!$store_member_grade){
                return json(['msg'=>'用户信息异常'],500);
            }
            //插入入驻信息
            $ma_data['mid']=UID;
            $ma_data['type']=$type;
            $ma_data['month']=$store_member_grade['month'];
            $ma_data['grade_id']=$store_member_grade['id'];
            $ma_data['money']=$store_member_grade['money'];
            $ma_data['create_at']=time();
            $ma_data['pay_time']=0;
            $ma_id=Db::name(ORDER_TYPE_ADMISSION_ORDER_TABLE)->insertGetId($ma_data);

            //插入支付信息
            $pl_data['order_sn']=create_order_sn(16,'admission');
            $pl_data['order_id']=$ma_id;
            $pl_data['money']=$ma_data['money'];
            $pl_data['type']=ORDER_TYPE_ADMISSION;
            $pl_data['pay_type']=PAY_TYPE_WEXIN;
            $pl_data['pay_status']=0;
            $pay_log_id=Db::name('pay_log')->insertGetId($pl_data);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
        //跳转到支付
        return action('api/other.pay/weixin',['pay_log_id'=>$pay_log_id,'code'=>$code]);
    }

    /**
     * 接收用户举报
     * @return \think\response\Json
     */
    public function report(){
        try{
            $post=$this->request->only(['desc','voucher','name','phone'],'post');
            $validate=new \app\api\validate\Report();
            if(!$validate->check($post)){
                return json(['msg'=>$validate->getError()],403);
            }
            $post['mid']=UID;
            $post['create_at']=time();
            //插入举报数据
            Db::name('report')->strict(false)->insert($post);
            return json(['msg'=>'举报成功,我们会尽快处理']);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 获取用户的关注列表
     * @return \think\response\Json
     */
    public function follow_list(){
        try{
            //查询关注的工人
            $worker=Db::name('member_follow')->alias('mf')
                ->join(['store_member'=>'m'],'m.id=mf.mid')
                ->join(['worker_info'=>'wi'],'m.id=wi.mid')
                ->where('mf.uid',UID)
                ->where('mf.member_type',USER_TYPE_WORKER)
                ->where('m.type',USER_TYPE_WORKER)
                ->where('wi.expiry_time','>',time())
                ->field('m.id,headimg,province,city,district,address,lng,lat,phone,wi.id wi_id,wi.name,good_at,work_price,skill,birthday')
                ->select();
            foreach ($worker as $k=>&$v){
                $v['full_address']=address_tostring($v,0,' ');
                $v['skill_arr']=Db::name('my_cate')->where('id','in',$v['skill'])->field('title')->select();
                $v['age']=date('Y')-date('Y',$v['birthday']);
                $v['authentication_type_text']=get_authentication_text($v['id']);
            }
            //查询关注的供应商
            $supplier=Db::name('member_follow')->alias('mf')
                ->join(['store_member'=>'m'],'m.id=mf.mid')
                ->join(['supplier_info'=>'si'],'m.id=si.mid')
                ->where('mf.uid',UID)
                ->where('mf.member_type',USER_TYPE_SUPPLIER)
                ->where('m.type',USER_TYPE_SUPPLIER)
                ->where('si.expiry_time','>',time())
                ->field('m.id,headimg,province,city,district,address,lng,lat,phone,si.id si_id,si.name,main')
                ->select();
            foreach ($supplier as $k=>&$v){
                $v['full_address']=address_tostring($v,0,' ');
                $v['main_arr']=Db::name('my_cate')->where('id','in',$v['main'])->field('title')->select();
            }
            $data['workers']=$worker;
            $data['suppliers']=$supplier;
            return json(['msg'=>'success','data'=>$data]);
        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 用户认证
     * @return \think\response\Json
     */
    public function authentication(){
        try{
            $type=$this->request->post('type');
            switch ($type){
                case AUTHENTICATION_PERSON:
                    //个人认证
                    $validate=new \app\api\validate\AuthenticationPerson();
                    $post=$this->request->only(['name','card_num','mobile','desc','hand_card','card_back'],'post');
                    break;
                case AUTHENTICATION_COMPANY:
                    //企业认证
                    $validate=new \app\api\validate\AuthenticationCompany();
                    $post=$this->request->only(['name','subject_type','license_num','mobile','license'],'post');
                    break;
                default:
                    return json(['msg'=>'认证类型不允许'],403);
            }
            if(!$validate->check($post)){
                return json(['msg'=>$validate->getError()],403);
            }
            //判断用户是否提交了该认证
            $authentication=Db::name('authentication')->where('mid',UID)->where('type',$type)->field('id,status')->find();
            if(!$authentication||$authentication['status']!=1){
                $data['mid']=UID;
                $data['content']=json_encode($post);
                $data['type']=$type;
                $data['status']=0;
                $data['create_at']=time();
                if(isset($authentication['id'])){
                    //更新
                    Db::name('authentication')->where('id',$authentication['id'])->update($data);
                }else{
                    //新增
                    Db::name('authentication')->insert($data);
                }
            }else{
                return json(['msg'=>'您已通过了实名认证'],403);
            }
            return json(['msg'=>'success']);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 获取用户认证信息
     * @return \think\response\Json
     */
    public function authentication_info(){
        try{
            //查询用户认证信息
            $type=$this->request->get('type');//认证类型
            $authentication=Db::name('authentication')->where('mid',UID)->where('type',$type)->find();
            if(isset($authentication['content'])){
                $content=json_decode($authentication['content'],true);
                unset($authentication['content']);
                $authentication=array_merge($authentication,$content);
                switch ($authentication['status']){
                    case -1:
                        $authentication['status_text']='未通过';
                        $authentication['class']='red';
                        break;
                    case 0:
                        $authentication['status_text']='待审核';
                        $authentication['class']='orange';
                        break;
                    case 1:
                        $authentication['status_text']='已认证';
                        $authentication['class']='green';
                        break;
                }
            }else{
                $authentication['status']=-2;
                $authentication['status_text']='未认证';
                $authentication['class']='gray';
            }
            return json(['msg'=>'success','data'=>$authentication]);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 缴纳诚意金
     * @return \think\response\Json
     */
    public function earnest(){
        try{
            $code=$this->request->get('code');

            //查询用户是否缴纳了诚意金
            $earnest=Db::name('earnest')->where('mid',UID)->where('status','<>',-1)->find();
            if(!$earnest){
                //没有记录 新增
                $e_data['mid']=UID;
                $e_data['money']=EARNEST_MONEY;
                $e_data['create_at']=time();
                $e_data['status']=0;
                $e_id=Db::name(ORDER_TYPE_EARNEST_ORDER_TABLE)->insertGetId($e_data);
            }else{
                if($earnest['status']==1){
                    //已缴纳诚意金
                    return json(['msg'=>'您已缴纳过保证金'],500);
                }else{
                    //有记录 未支付
                    $e_id=$earnest['id'];
                    $e_data['money']=$earnest['money'];
                }
            }

            //插入支付信息
            $pl_data['order_sn']=create_order_sn(16,'earnest');
            $pl_data['order_id']=$e_id;
            $pl_data['money']=$e_data['money'];
            $pl_data['type']=ORDER_TYPE_EARNEST;
            $pl_data['pay_type']=PAY_TYPE_WEXIN;
            $pl_data['pay_status']=0;
            $pay_log_id=Db::name('pay_log')->insertGetId($pl_data);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
        //跳转到支付
        return action('api/other.pay/weixin',['pay_log_id'=>$pay_log_id,'code'=>$code]);
    }

    /**
     * 获取保证金缴纳信息
     * @return \think\response\Json
     */
    public function earnest_info(){
        try{
            $earnest=Db::name(ORDER_TYPE_EARNEST_ORDER_TABLE)->where('mid',UID)->where('status',1)->field('money,FROM_UNIXTIME(create_at,\'%Y/%m/%d %H:%i\') as create_at')->find();
            if(!$earnest){
                $data['state_of_payment']=0;
                $data['class']='red';
                $data['state_of_payment_text']='未缴纳';
            }else{
                $data['state_of_payment']=1;
                $data['class']='green';
                $data['state_of_payment_text']='已缴纳';
                $data=array_merge($data,$earnest);
            }
            return json(['msg'=>'success','data'=>$data]);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }
    /**
     * 关注/取消关注用户
     * @return \think\response\Json
     */
    public function follow()
    {
        try{
            $mid=input('mid');
            $attach_id=input('attach_id');
            //查询这个人关注了这个经销商没有
            $count=Db::name('member_follow')->where('uid',UID)->where('mid',$mid)->count();
            if($mid==UID){
                return json(['msg'=>'您不能关注自己'],500);
            }
            if($count>0){
                //取消关注
                DB::name('member_follow')->where('uid',UID)->where('mid',$mid)->delete();
                $msg='取消成功';
            }else{
                //查询这个用户类型
                $user_type=Db::name('store_member')->where('id',$mid)->value('type');
                //关注
                $data['uid']=UID;
                $data['mid']=$mid;
                $data['attach_id']=$attach_id;
                $data['member_type']=$user_type;
                $data['create_at']=time();
                DB::name('member_follow')->insert($data);
                $msg='关注成功';
            }
            return json(['msg'=>$msg]);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 用户给别人发布的内容点赞/取消点赞
     * @return \think\response\Json
     */
    public function praise(){
        try{
            $attach_id=input('attach_id');
            $type=input('type',1);//（1：案例  2：动态  3：文章）
            //查询是否给这个对象点赞了
            $count=Db::name('praise')->where('mid',UID)->where('attach_id',$attach_id)->where('type',$type)->count();
            if($count>0){
                //取消点赞
                DB::name('praise')->where('mid',UID)->where('attach_id',$attach_id)->delete();
                $msg='取消成功';
                log_credit_change(UID,-PRAISE_CREDIT,PRAISE,'文章取消点赞减信用积分');
            }else{
                //点赞
                $data['mid']=UID;
                $data['attach_id']=$attach_id;
                $data['type']=$type;
                $data['create_at']=time();
                DB::name('praise')->insert($data);
                $msg='点赞成功';
                log_credit_change(UID,PRAISE_CREDIT,PRAISE,'文章点赞加信用积分');
            }
            $praised_num=Db::name('praise')->where('type',$type)->where('attach_id',$attach_id)->count();
            return json(['msg'=>$msg,'data'=>$praised_num]);
        }catch(Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 用户收藏案例/动态/文章
     * @return \think\response\Json
     */
    public function collection(){
        try{
            $attach_id=input('attach_id');
            $type=input('type',1);//（1：案例  2：动态  3：文章）
            //查询是否给这个对象点赞了
            $count=Db::name('collection')->where('mid',UID)->where('attach_id',$attach_id)->where('type',$type)->count();
            if($count>0){
                //取消收藏
                DB::name('collection')->where('mid',UID)->where('attach_id',$attach_id)->delete();
                $msg='取消成功';
            }else{
                switch ($type){
                    case 1:
                        $model='member_case';
                        break;
                    case 2:
                        $model='dynamic';
                        break;
                    case 3:
                        $model='article';
                        break;
                }
                //收藏
                $data['mid']=UID;
                $data['attach_id']=$attach_id;
                $data['type']=$type;
                $data['model']=$model;
                $data['create_at']=time();
                DB::name('collection')->insert($data);
                $msg='收藏成功';
            }
            return json(['msg'=>$msg]);
        }catch(Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 我的收藏
     * @return \think\response\Json
     */
    public function my_collection(){
        try{
            $type=input('type');//（1：案例  2：动态  3：文章）
            $page_now = input('page_now',1);
            $page_size = input('page_size',10);
            $db=Db::name('collection')->where('mid',UID);
            if($type){
                $db->where('type',$type);
            }
            $list=$db->page($page_now,$page_size)->select();
            foreach ($list as $k=>&$v){
                $v['author']=Db::name($v['model'])->where('id',$v['attach_id'])->value('mid');
                $v['create_at']=date('Y.m.d H:i:s',$v['create_at']);
                $field='id,mid,images';
                if($v['type']!=2)$field.=',title';
                if($v['type']==3)$field.=',video_url';
                $v['attach']=Db::name($v['model'])->where('id',$v['attach_id'])->field($field)->find();
                if(!$v['attach']){
                    unset($list[$k]);
                }
                isset($v['attach']['images'])?$v['attach']['images']=explode('|',$v['attach']['images']):'';
            }
            return json(['msg'=>'success','data'=>$list]);
        }catch(Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 签到
     * @return \think\response\Json
     */
    function sign(){
        //查询今天是否签到了
        $today=strtotime(date('Y-m-d'));
        $sign=Db::name('member_sign')
            ->where('mid',UID)
            ->where('addtime',$today)
            ->count();
        if($sign>0){
            return json(['msg'=>'您已签到,明天再来吧'],500);
        }
        //签到
        Db::name('member_sign')
            ->insert([
                'mid'=>UID,
                'addtime'=>$today
            ]);
        log_credit_change(UID,SIGN_IN_CREDIT,SIGN_IN,'签到加信用积分');
        return json(['msg'=>'签到成功'],200);
    }

    function money_list(){
        //查询该会员的团币流水
        $page_now=input('page_now',1);
        $page_size=input('page_size',20);
        $account_log=Db::name('account_log')
            ->where('mid',UID)
            ->where('money','<>',0)
            ->field('money,FROM_UNIXTIME(addtime,\'%Y-%m-%d\') addtime,`desc`')
            ->page($page_now,$page_size)
            ->select();

        return json(['msg'=>'success','data'=>$account_log]);
    }

    function credit_list(){
        //查询该会员的团币流水
        $page_now=input('page_now',1);
        $page_size=input('page_size',20);
        $credit_log=Db::name('credit_log')
            ->where('mid',UID)
            ->where('credit','<>',0)
            ->field('credit,FROM_UNIXTIME(addtime,\'%Y-%m-%d\') addtime,remark')
            ->page($page_now,$page_size)
            ->select();

        return json(['msg'=>'success','data'=>$credit_log]);
    }
}